<?php

App::uses('RealtyAppController', 'Realty.Controller');

/**
 * Realty Controller
 *
 * @категория:  Controller
 * @пакет:      Croogo.Categories.Controller
 * @версия:     1.0
 * @автор:      Калистратов Сергей Михайлович
 * @почта:      kalistratov.s.m@gmail.com
 * @телефон:    +7 (987) 310-56-02
 * @ссылка:     http://www.croogo.org
 */

class CategoriesController extends RealtyAppController{

/**
 * Имя контроллера для совместимости с php4
 *
 * @var string
 * @access public
 */
	public $name = 'Categories';

/**
 * Добавление компонентов для текущего контроллера
 */
	public $components = array(
		'Paginator'
	);

/**
 * Добавление хелперов для текущего контроллера
 */
	public $helpers = array(
		'Ckeditor.Ckeditor',
	);

/**
 * BeforeFilter
 * Снимаем защиту для экшенов
 *
 * @return void
 * @access public
 */
	public function beforeFilter() {
		parent::beforeFilter();
		$this->Security->unlockedActions = array(
			'admin_toggle',
			'admin_process',
			'admin_delete',
		);
	}

/**
 * Изменение статуса категории
 *
 * @param $id string Category id
 * @param $status integer Current Category status
 * @return void
 */
	public function admin_toggle($id = null, $status = null) {
		$this->Croogo->fieldToggle($this->Category, $id, $status);
	}

/**
 * Admin index
 *
 * @return void
 * @access public
 */
	public function admin_index(){
		$this->Category->recursive = 0 ;
		$categoriesTree = $this->Category->generateTreeList();
		$categoriesStatus = $this->Category->find('list' , array(
			'fields' => array(
				'Category.id',
				'Category.status',
			),
		));
		$categories = $this->Category->find('all');
		$this->set(compact('categoriesTree' , 'categoriesStatus' , 'categories'));
	}

/**
 * Admin add
 *
 * @return void
 * @access public
 */
	public function admin_add(){
		if ($this->request->is('post')) {
			$this->Category->create();
			if ($this->Category->save($this->request->data)) {
				$this->Session->setFlash(__d('croogo', 'Категория %s была сохранена' , sprintf('<strong>%s</strong>' , $this->request->data['Category']['title'])),
					'default', array('class' => 'success')
				);
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__d('croogo', 'Категория не может быть сохранена. Попробуйте ещё раз.'), 'default', array('class' => 'error'));
			}
		}
		$categories = $this->Category->generateTreeList();
		$this->set(compact('categories'));
	}

/**
 * Admin edit
 *
 * @access public
 */
	public function admin_edit($id = null) {
		if (!$this->Category->exists($id)) {
			throw new NotFoundException(__d('croogo', 'Данной категории не существует'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->Category->save($this->request->data)) {
				$this->Session->setFlash(__d('croogo', 'Категория %s была изменена' , sprintf('<strong>%s</strong>' , $this->request->data['Category']['title'])), 'default', array('class' => 'success'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__d('croogo', 'Категория не может быть сохранена. Попробуйте ещё раз.'), 'default', array('class' => 'error'));
			}
		} else {
			$options = array('conditions' => array('Category.' . $this->Category->primaryKey => $id));
			$this->request->data = $this->Category->find('first', $options);
		}
		$categories = $this->Category->ParentCategory->find('list');
		$this->set(compact('categories'));
	}

/**
 * Admin delete
 *
 * integer $id
 * @access public
 */
	public function admin_delete($id = null) {
		$this->Category->id = $id;
		if (!$this->Category->exists()) {
			throw new NotFoundException(__d('croogo', 'Invalid category'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->Category->delete()) {
			$this->Session->setFlash(__d('croogo', 'Категория удалена'), 'default', array('class' => 'success'));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__d('croogo', 'Категория не может быть удалена'), 'default', array('class' => 'error'));
		$this->redirect(array('action' => 'index'));
	}

/**
 * Admin movedown
 *
 * @param integer $id
 * @param integer $step
 * @return void
 * @access public
 */
	public function admin_movedown($id, $step = 1) {
		$category = $this->Category->findById($id);

		if (!isset($category['Category']['id'])) {
			$this->Session->setFlash(__d('croogo', 'Invalid id for Category'), 'default', array('class' => 'error'));
			$this->redirect(array(
				'plugin' => 'realty',
				'controller' => 'category',
				'action' => 'index',
			));
		}

		$this->Category->Behaviors->attach('Tree', array(
			'Category.id' => $id,
		));

		if ($this->Category->moveDown($id, $step)) {
			$this->Session->setFlash(__d('croogo', 'Moved down successfully'), 'default', array('class' => 'success'));
		} else {
			$this->Session->setFlash(__d('croogo', 'Could not move down'), 'default', array('class' => 'error'));
		}
		$this->redirect(array(
			'plugin' => 'realty' ,
			'controller' => 'categories' ,
			'action' => 'index'
		));
	}

/**
 * Admin moveup
 *
 * @param integer $id
 * @param integer $step
 * @return void
 * @access public
 */
	public function admin_moveup($id, $step = 1) {
		$category = $this->Category->findById($id);

		if(!isset($category['Category']['id'])){
			$this->Session->setFlash(__d('croogo', 'Invalid id for Category'), 'default', array('class' => 'error'));
			$this->redirect(array(
				'plugin' => 'realty',
				'controller' => 'categories',
				'action' => 'index',
			));
		}

		$this->Category->Behaviors->attach('Tree', array(
			'Category.id' => $id,
		));

		if ($this->Category->moveUp($id, $step)) {
			$this->Session->setFlash(__d('croogo', 'Moved up successfully'), 'default', array('class' => 'success'));
		} else {
			$this->Session->setFlash(__d('croogo', 'Could not move up'), 'default', array('class' => 'error'));
		}

		$this->redirect(array(
			'plugin' => 'realty',
			'controller' => 'categories',
			'action' => 'index'
		));

	}

/**
 * Admin process
 *
 * @param integer $menuId
 * @return void
 * @access public
 */
	public function admin_process($CategoryId = null){
		$action = $this->request->data['Category']['action'];
		$ids = array();

		foreach ($this->request->data['Category'] as $id => $value) {
			if ($id != 'action' && $value['id'] == 1) {
				$ids[] = $id;
			}
		}

		if (count($ids) == 0 || $action == null) {
			$this->Session->setFlash(__d('croogo', 'No items selected.'), 'default', array('class' => 'error'));
			$this->redirect(array(
				'controller' => 'categories',
				'action' => 'index',
			));
		}

		if ($action == 'delete' &&
			$this->Category->deleteAll(array('Category.id' => $ids), true, true)) {
			$this->Session->setFlash(__d('croogo', 'Category deleted.'), 'default', array('class' => 'success'));
		} elseif ($action == 'publish' &&
			$this->Category->updateAll(array('Category.status' => 1) , array('Category.id' => $ids))){
			$this->Session->setFlash(__d('croogo' , 'Category published') , 'default' , array('class' => 'success'));
		} elseif ($action == 'unpublish' &&
			$this->Category->updateAll(array('Category.status' => 0) , array('Category.id' => $ids))){
			$this->Session->setFlash(__d('croogo' , 'Category unpublished') , 'default' , array('class' => 'success'));
		} else {
			$this->Session->setFlash(__d('croogo' , 'An error occurred') , 'default' , array('class' => 'error'));
		}

		$this->redirect(array(
			'controller' => 'categories',
			'action' => 'index'
		));
	}
}